package com.acxy.ants.core;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-04-26
 */

import com.acxy.ants.common.kit.StrKit;
import com.acxy.ants.core.config.*;
import com.acxy.ants.core.handler.RenderHandler;
import com.acxy.ants.core.kit.LogKit;
import com.acxy.ants.resful.Mapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import java.util.List;


/**
 * Ants
 */
public final class AntsContext {

    private static final Logger logger = LoggerFactory.getLogger(AntsContext.class);

    private static final Constants constants = new Constants();
    private static final Plugins plugins = new Plugins();
    private static final Interceptors interceptors = new Interceptors();
    private static final Handlers handlers = new Handlers();

    public AntsContext(AntsConfig antsConfig){
        this(antsConfig, null, null);
    }

    public AntsContext(AntsConfig antsConfig, String[] modules, ServletContext servletContext) {

        logger.debug("_____________________初始化自定义配置______________________");

        //初始化常量
        antsConfig.configConstant(constants);
        logger.debug("初始化自定义常量[constants]加载完成...");

        if(StrKit.notBlank(modules) && servletContext != null) {
            String webINF = servletContext.getRealPath("/WEB-INF");
            Modules.initModules(webINF, modules);
            logger.debug("初始化模块[modules]加载完成...");
        }


        logger.debug("_____________________初始化系统加载配置______________________");

        //初始化插件
        antsConfig.configPlugin(plugins);
        startPlugins();
        logger.debug("初始化自定义插件[plugins]加载完成...");
        //初始化拦截器
        antsConfig.configInterceptor(interceptors);
        logger.debug("初始化自定义拦截器[interceptors]加载完成...");
        //初始化自定义handler集合
        antsConfig.configHandler(handlers);
        logger.debug("初始化自定义请求链[handlers]加载完成...");
        //TODO 扫描类文件形成动态代理 Service注解 有接口采用JDK代理 无接口采用CGLIB代理
        Services.registerServices(constants.getServicePackage(), constants.isDebug());
        logger.debug("初始化系统Service配置加载完成...");

        //扫描类文件形成URL与方法映射集合 Controller注解
        Mapping.registerMappings(constants.getControllerPackage(), constants.getRegexSuffix(), constants.isDebug());
        logger.debug("初始化系统URL映射配置加载完成...");

        //初始化完成 打印输出logo
        logger.info("\n┏━━━━━━━━━━━━━━━━━━━━┓\n"+
                "┃        Ants  Start  Success !       ┃\n"+
                "┗━━━━━━━━━━━━━━━━━━━━┛\n"+
                ">>> Web Ants :: 初始化完成 Success!\n");
    }

    /**
     * 得到常量
     *
     * @return
     */
    public Constants getConstants() {
        return constants;
    }

    /**
     * 得到handler链表
     *
     * @return
     */
    public Handlers getHandlers() {
       handlers.setConstants(constants);
       handlers.add(new RenderHandler(constants));
       return handlers;
    }


    private void startPlugins() {
        List<Plugin> pluginList = Plugins.getPluginList();
        if (pluginList == null) return;
        for (Plugin plugin : pluginList) {
            try {
                if (plugin.start() == false) {
                    String message = "Plugin start error: " + plugin.getClass().getName();
                    logger.error(message);
                    throw new RuntimeException(message);
                }
            } catch (Exception e) {
                String message = "Plugin start error: " + plugin.getClass().getName() + ". \n" + e.getMessage();
                logger.error(message);
                throw new RuntimeException(message, e);
            }
        }
    }

    private void stopPlugins() {
        List<Plugin> pluginList = Plugins.getPluginList();
        if (pluginList != null) {
            for (int i = pluginList.size() - 1; i >= 0; i--) {        // stop plugins
                boolean success = false;
                try {
                    success = pluginList.get(i).destroy();
                } catch (Exception e) {
                    success = false;
                    logger.error(e.getMessage());
                }
                if (!success) {
                    System.err.println("Plugin stop error: " + pluginList.get(i).getClass().getName());
                }
            }
        }
    }

}










